package com.celeritymq.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectUtil {

	public static byte[] parse(Serializable target) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(target);
			oos.flush();
			bos.close();
			oos.close();
			byte[] array = bos.toByteArray();
			return array;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Object recover(byte[] array) throws Exception {
		ByteArrayInputStream bis = new ByteArrayInputStream(array);
		ObjectInputStream ois = new ObjectInputStream(bis);
		Object o = ois.readObject();
		return o;
	}

	public static byte[] parse(int v) {
		byte[] valueArray = new byte[4];
		valueArray[0] = (byte) (v >>> 24);
		valueArray[1] = (byte) (v >>> 16);
		valueArray[2] = (byte) (v >>> 8);
		valueArray[3] = (byte) v;
		return valueArray;
	}

	public static int recoverInt(byte[] valueArray) {
		int v = 0;
		v = (((int) valueArray[0] & 0xFF) << 24);
		v = v + (((int) valueArray[1] & 0xFF) << 16);
		v = v + (((int) valueArray[2] & 0xFF) << 8);
		v = v + ((int) valueArray[3] & 0xFF);
		return v;
	}

	public static void main(String[] args) {
		int k = Integer.MAX_VALUE;
		byte[] ka = parse(k);
		int k2 = recoverInt(ka);
		System.out.println(k2);
	}

}
